import pyautogui
import time
import subprocess
import os
import pyperclip
import ctypes
import win32clipboard
from selenium import webdriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.common.by import By

# 设置安全保护
pyautogui.FAILSAFE = True
pyautogui.PAUSE = 1


def copy_file_to_windowsclipboard(file_path:str):
        '''file_path:文件的绝对路径\n
        该方法将给定绝对路径的文件复制到windows系统下的剪贴板\n'''
        os.environ.update({"__COMPAT_LAYER":"RUnAsInvoker"})#添加管理员权限
        class DROPFILES(ctypes.Structure):
            _fields_ = [
                ("pFiles", ctypes.c_uint),
                ("x", ctypes.c_long),
                ("y", ctypes.c_long),
                ("fNC", ctypes.c_int),
                ("fWide", ctypes.c_bool),
            ]
        pDropFiles = DROPFILES()
        pDropFiles.pFiles = ctypes.sizeof(DROPFILES)
        pDropFiles.fWide = True
        #获取文件绝对路径
        files = file_path.replace("/", "\\")
        data=files.encode("U16")[2:] + b"\0\0" #结尾一定要两个\0\0字符，这是规定
        win32clipboard.OpenClipboard() #打开剪贴板（独占）
        try:
            #若要将信息放在剪贴板上，首先需要使用 EmptyClipboard 函数清除当前的剪贴板内容
            win32clipboard.EmptyClipboard() #清空当前的剪贴板信息
            win32clipboard.SetClipboardData(win32clipboard.CF_HDROP,bytes(pDropFiles)+data)#设置当前剪贴板数据
        except Exception:
            print("复制文件到剪贴板时出错！")
        finally:
            win32clipboard.CloseClipboard() #关闭剪贴板（释放独占）

def get_screenshot():
    """
    打开网页、点击查询和保存按钮，获取截图文件的具体路径
    返回：截图文件的完整路径
    """
    # 配置Edge浏览器
    edge_service = Service(r"D:\rjaz\qudong\edgedriver_win64\msedgedriver.exe")
    options = Options()
    
    # 设置下载目录
    download_dir = os.path.join(os.getcwd(), "screenshots")
    os.makedirs(download_dir, exist_ok=True)
    
    # 配置浏览器下载选项
    prefs = {
        "download.default_directory": download_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.enabled": True
    }
    options.add_experimental_option("prefs", prefs)
    
    # 启动浏览器并访问页面
    driver = webdriver.Edge(service=edge_service, options=options)
    driver.get("http://10.46.41.221:5000/dataview/shiduan")
    time.sleep(3)  # 等待页面加载
    
    # 执行查询操作
    try:
        query_button = driver.find_element(By.XPATH, "//button[@type='submit']")
        query_button.click()
        print("已点击查询按钮")
    except Exception as e:
        print(f"定位查询按钮失败: {e}")
    
    time.sleep(5)  # 查询后等待5秒
    
    # 记录保存前的文件列表
    before_files = set(os.listdir(download_dir))
    
    # 执行保存操作
    try:
        save_button = driver.find_element(By.ID, "save-button")
        save_button.click()
        print("已点击保存按钮")
    except Exception as e:
        print(f"定位保存按钮失败: {e}")
    
    time.sleep(5)  # 等待保存完成
    driver.quit()
    
    # 查找新保存的文件
    after_files = set(os.listdir(download_dir))
    new_files = after_files - before_files
    
    if new_files:
        # 获取最新保存的文件
        new_file_paths = [os.path.join(download_dir, f) for f in new_files]
        latest_file = max(new_file_paths, key=os.path.getmtime)
        print(f"找到新保存的图片文件: {latest_file}")
        return latest_file
    else:
        print("未找到新保存的文件，返回下载目录")
        return download_dir
    
def open_application_and_paste_image(app_path, image_path):
    """
    打开应用程序并自动粘贴图片路径
    参数:
    app_path (str): 应用程序路径
    image_path (str): 图片文件路径
    """
    try:
        # 检查文件是否存在
        if not os.path.isfile(app_path):
            print(f"错误：应用程序不存在 - {app_path}")
            return
        
        # 启动应用并最大化
        subprocess.Popen([app_path])
        time.sleep(3)  # 等待应用启动
        pyautogui.hotkey('win', 'up')  # 最大化窗口
        time.sleep(1)
        
        print(f"成功打开应用并最大化窗口: {app_path}")
        
        # 输入文字并确认
        pyautogui.click(30, 70)
        time.sleep(2)
        pyautogui.click(190, 70)
        time.sleep(1)
        #pyperclip.copy("S7计量沟通群")
        pyperclip.copy("API测试")
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(3)
        pyautogui.press('enter', presses=2, interval=0.2)

        pyautogui.click(1020, 985)
        time.sleep(2)
        copy_file_to_windowsclipboard(image_path)
        time.sleep(2)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(3)
        pyautogui.press('enter', presses=2, interval=0.2)

    except Exception as e:
        print(f"操作过程中出现错误: {e}")

# 主函数
def main():
    app_path = r"D:\rjaz\新建文件夹\itongweiplus\itongweiplus.exe"
    # 获取截图并打开应用
    image_path = get_screenshot()
    open_application_and_paste_image(app_path, image_path)

if __name__ == "__main__":
    main()
    